package handler

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"math/rand"
	"strconv"
	"time"
	"zy12/global"
	"zy12/model"
	"zy12/pkg/ALiYun"
	"zy12/pkg/jwt"
	"zy12/reporsitory"
	"zy12/request"
	"zy12/response"
)

const SEND_ALY = "send:"
const JWT_LOGIN = "2210A"

func Send(c *gin.Context) {
	var req request.SendRedis
	err := c.ShouldBind(&req)
	if err != nil {
		response.ResponseError(c, "错误", err.Error())
		return
	}
	code := rand.Intn(9000) + 1000
	suss, err := ALiYun.Suss(req.Mobile, strconv.Itoa(code))
	if err != nil {
		fmt.Println(suss)
		return
	}
	global.Rdb.Set(context.Background(), SEND_ALY+req.Mobile, code, time.Minute*30)
}

func Login(c *gin.Context) {
	var data request.LoginUser
	i, _ := global.Rdb.Get(context.Background(), JWT_LOGIN+data.Mobile).Int()
	if i != data.Code {
		response.ResponseError(c, "验证码不正确", nil)
	}
	err := c.ShouldBind(&data)
	if err != nil {
		response.ResponseError(c, "错误", err.Error())
		return
	}

	login := model.User{}
	reporsitory.Login(&model.User{
		Mobile: data.Mobile,
	}, &login)
	if login.Id == 0 {
		register := model.User{
			Mobile:   data.Mobile,
			Password: data.Password,
		}
		reporsitory.Create(&register)
		if register.Id == 0 {
			response.ResponseError(c, "注册失败", nil)
			return
		}
	}
	if login.Password != data.Password {
		response.ResponseError(c, "密码错误", nil)
	}
	claims := jwt.CustomClaims{ID: login.Id}
	token, err := jwt.NewJWT(JWT_LOGIN).CreateToken(claims)
	if err != nil {
		response.ResponseError(c, "token生成失败", err)
		return
	}
	response.ResponseSuccess(c, "登陆成功", token)

}
